package com.xuzao.developer.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;

/**
 * @description TODO
 * @author xuzao
 * @date   2019-04-01 11:05
 */
@Slf4j
public class Base64Util {
    /**
     * 编码
     *
     * @param binaryData
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encode(String binaryData) throws UnsupportedEncodingException {
        return new String(Base64.encodeBase64(binaryData.getBytes()), "UTF-8");
    }

    /**
     * 编码
     *
     * @param bytes
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encode(byte[] bytes) {
        String str = "";
        try {
            str = new String(Base64.encodeBase64(bytes), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("Base64Util error",e);
        }
        return str;
    }
    /**
     * 编码
     *
     * @param bytes
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] encodeByte(byte[] bytes) {
        return Base64.encodeBase64(bytes);
    }

    /**
     * 解码
     *
     * @param base64String
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String decode(String base64String) {
        String str = "";
        try {
            str =  new String(Base64.decodeBase64(base64String.getBytes("UTF-8")), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("Base64Util error",e);
        }
        return str;
    }

    /**
     * 解码
     *
     * @param base64String
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] decodeByByte(String base64String) {
        byte[] bytes = null;
        try {
            bytes =  Base64.decodeBase64(base64String.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("Base64Util error",e);
        }
        return bytes;
    }

    /**
     * 解码
     *
     * @param base64String
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] decodeByByte(byte[] base64String) {
        byte[] bytes = null;
        try {
            bytes =  Base64.decodeBase64(base64String);
        } catch (Exception e) {
            log.error("Base64Util error",e);
        }
        return bytes;
    }
}
